Crate looking_glass[−][src]
Expand description
Looking Glass provides reflection for virtually any Rust type. It does this through a set of traits, and type-erasing enums.
We allow the user to store any type, regardless of lifetime, through a trait called Instance
.
Instance
has a lifetime attached to it,
that outlives the lifetime of any type it downcasts to.
This ensures that lifetime guarantee are maintained at compile-time.
Much like std::any::Any
, we perform runtime type-checks to ensure type-safety.
Generally it is best to use the derive macros from looking_glass_derive
to implement the various traits here,
as care must be taken when implementing them to not enable
undefined behaviour. Check out the docs for Value
, StructInstance
, VecInstance
,
OptionInstance
, and EnumInstance
for
Examples
Struct reflection
use looking_glass::Typed;
use looking_glass_derive::Instance;
#[derive(Instance, Clone, PartialEq)]
struct Foo {
text: String,
int: i32,
}
let test = Foo { text: "Test".to_string(), int: -2 };
let val = test.as_value();
let inst = val.as_reflected_struct().unwrap();
let value = inst.get_value("text").expect("field not found");
let text = value.as_ref().borrow::<&String>().expect("borrow failed");
assert_eq!(text, &test.text);
Vec reflection
use looking_glass::{Typed, VecInstance};
let vec = vec!["test".to_string(), "123".to_string(), "foo".to_string()];
let first = vec.get_value(0).expect("get value failed");
assert_eq!(first, "test".to_string().as_value());
Safety Details
We can’t use std::any::TypeId
, like std::any::Any
does.
So instead we create an enum called ValueTy
that describes the reflected type.
ValueTy
internally stores the std::any::TypeId
of a type.
For types with generic lifetimes (or non-static lifetimes) we require that the implementer
return the std::any::TypeId
of the static version of that type.
Imagine a struct defined like: struct Foo<'a>(&'a str)
.
The ValueTy
for this type would be constructed like so:
let _ = ValueTy::Struct(std::any::TypeId::of::<Foo<'static>>());
Structs
A cheaply cloneable and sliceable chunk of contiguous memory.
As tree structure that repersents a set of nested fields.
A SmolStr
is a string type that has the following properties:
A container for a type-erased value.
Enums
A reflected field of an enum
An enum containing an owned copy of a Value
A description of a reflected type
Traits
A extension trait that provides downcasting
A reflected enum
Any reflected type
A ext trait for looking_glass_derive
meant to consume a OwnedValue
and return T
A reflected Option
A reflected struct
A reflected Vec